<?php
namespace org\crawlgenie\application\base;
use org\crawlgenie\application\environment\Request;
use org\crawlgenie\application\document\Document;
use org\crawlgenie\application\document\Renderer;
use org\crawlgenie\application\database\Database;
use org\crawlgenie\application\registry\Registry;
use \CGException;
use \CGConfig;
use \Logger;

/**
 *  Factory class to instantiate various core framework objects
 *
 *  @author $Author: jinsonxu@gmail.com $:
 *  $Date: 2014-11-09 22:57:19 +0000 (Sun, 09 Nov 2014) $:
 *  $Id: Factory.php 6 2014-11-09 22:57:19Z jinsonxu@gmail.com $:
 *  @version $Rev: 6 $:
 *  @package crawlgenie.application
 *  @subpackage base
 */
class Factory {

    /**
     * Factory method to create and return the requested Document instance
     * @param   string  $docType    The document type to create
     * @return  
     */
    public static function createDocument($docType) {
        if(in_array(strtoupper($docType), Renderer::getValidViewTypes()) === true) {
            $className = 'org\crawlgenie\application\document\Document' . strtoupper($docType);
            return new $className;
        } else {
            throw new CGException('Attempt to create invalid document type ' . $docType);
        }
    }



    /**
     * Factory method to init and return the proper Document object for the current request
     *
     * @return  <Document>  A subclass of the abstract Document class, depending on the requested view type
     */
    public static function getDocument() {
        $documentType = Request::getParam('response_format') !== null ? strtoupper(Request::getParam('response_format')) : strtoupper('html');
        
        Logger::getLogger(__CLASS__)->warn(__METHOD__ . ': Response DocumentType -> ' . $documentType);

        if(in_array($documentType, Renderer::getValidViewTypes()) === true) {
            $rendererClass = 'org\crawlgenie\application\document\Renderer' . strtoupper($documentType);
            $document = self::createDocument($documentType);
            $document->setRenderer(new $rendererClass());
            return $document;
            
        } else {
            throw new CGException('Attempt to create invalid response Document type ' . $documentType);
        }
    }


    
    public static function getDBConn() {
        if(!Registry::checkExists('org\crawlgenie\application\database\DatabasePDO')) {
            $db = Database::getConnection();
            Registry::addObj($db);
            return Registry::getObj('org\crawlgenie\application\database\DatabasePDO');
        } else {
            return Registry::getObj('org\crawlgenie\application\database\DatabasePDO');
        }
    }

}
?>
